package com.java2020.online_mall.dao;

import com.alibaba.druid.util.StringUtils;
import com.java2020.online_mall.model.User;
import com.java2020.online_mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackgeName: com.java2020.online_mall.dao
 * @Author: MNHK
 * Date: 2020/5/2 21:42
 * @Version:1.8
 */

public class UserDaoImpl implements UserDao{

    QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());

    @Override
    public List<User> allUser() {
        List<User> users = null;
        try {
            users = queryRunner.query("select * from user",
                    new BeanListHandler<User>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    @Override
    public int deleteUser(String id) {

        try {
            queryRunner.update("delete from user where id = ?",id);
        } catch (SQLException e) {
            e.printStackTrace();
            return 500;
        }
        return 200;
    }

    @Override
    public List<User> getSearchUser(String param) {
        Map<String, Object> dynamicSql = getDynamicSqlParam(param);
        String sql = (String) dynamicSql.get("sql");
        List<String> paramList = (List<String>) dynamicSql.get("param");

        List<User> users = null;
        try {
            users = queryRunner.query(sql,
                    new BeanListHandler<User>(User.class),
                    paramList.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    /**
     * 拼接法构建动态Sql语句
     * @param param
     * @return
     */
    private Map<String,Object> getDynamicSqlParam(String param) {
        String baseSql = "select * from user where 1=1";
        List<String> list = new ArrayList<>();
        if(!StringUtils.isEmpty(param)){
            baseSql = baseSql + " and nickname like ?";
            list.add("%" + param + "%");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sql", baseSql);
        map.put("param", list);
        return map;
    }
}
